package com.itqf.ipmsys.controller;


import com.itqf.ipmsys.dto.LoginDto;
import com.itqf.ipmsys.entity.Admin;
import com.itqf.ipmsys.entity.Police;
import com.itqf.ipmsys.service.AdminService;
import com.itqf.ipmsys.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 管理员表 前端控制器
 * </p>
 *
 * @author corn
 * @since 2021-09-22
 */
@CrossOrigin("*")
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 登录
     * @param loginDto
     * @return
     */
    @PostMapping(value = "login", consumes = "application/json;charset=utf-8")
    public Object login(@RequestBody LoginDto loginDto , HttpServletRequest request, HttpServletResponse response){

        //1、校验传入的参数是否正确
        if(StringUtils.isEmpty(loginDto.getAccount()) ||
                StringUtils.isEmpty(loginDto.getPassword())){
            return ResponseUtil.badArgumentValue();
        }

        //3、认证操作
        //1)subject
        Subject subject = SecurityUtils.getSubject();
        //2）usernameAndpasswordToken
        UsernamePasswordToken token = new UsernamePasswordToken(loginDto.getAccount(), loginDto.getPassword());
        //3）认证
        //4)try/catch 捕捉认证错误
        try{
            subject.login(token);
        }catch (AuthenticationException e){
            //认证错误
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_AUTH);
        }

        //4、认证通过，修改 ip / 登录时间
        String ip = request.getRemoteAddr();
        Date date = new Date();
        Admin admin = (Admin) subject.getPrincipal();

        int rows = adminService.updateAdminById(admin.getId(), ip, date);

        //认证成功以后，修改ip和登录时间失败
        //if(rows == 0){
        //    LOGGER.warn("[AdminAuthController:login]-->[认证成功以后，修改ip和登录时间失败！]-->" +
        //            "[未知]-->[未知]-->[id:ip:time]:{}:{}:{}", dtsAdmin.getId(), ip, date);
        //
        //}
        String key = (ip + UUID.randomUUID()).replaceAll("-", "");
        String value = JSONUtil.Obj2JSON(admin);
        if(loginDto.getRemomberme() == 1){
            stringRedisTemplate.opsForValue().set(key, value, 7, TimeUnit.DAYS);
        }else{
            stringRedisTemplate.opsForValue().set(key, value, 30, TimeUnit.MINUTES);
        }


        Cookie cookie = new Cookie("adminToken", key);
        cookie.setPath("/**");
        if(loginDto.getRemomberme() == 1){
            cookie.setMaxAge( 7 * 24 * 60 * 60);
        }else{
            cookie.setMaxAge( 30 * 60);
        }

        response.addCookie(cookie);

        Admin adm = adminService.findAdminByAccount(loginDto.getAccount());
        adm.setPassword("");

        return R.ok().setData("user",adm);
    }

    /**
     * 警员密码重置
     * @param police
     * @return
     */
    public int resetPassword(Police police) {
        //1. 根据用户id,调用用户服务,重置密码
        return adminService.resetPassword(police);
    }
}

